<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import DefaultLayout from '@/components/layout/DefaultLayout.vue'
import { useBlogStore } from '@/store/blog'
import { useCommentStore } from '@/store/comment'
import { useAuthStore } from '@/store/auth'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const blogStore = useBlogStore()
const commentStore = useCommentStore()
const authStore = useAuthStore()

const blog = ref(null)
const comments = computed(() => commentStore.comments)
const loading = ref(true)
const commentContent = ref('')
const replyContent = ref('')
const activeReplyId = ref(null)
const commentLoading = ref(false)
const replyLoading = ref(false)
const likeLoading = ref(false)

const isAuthenticated = computed(() => authStore.isAuthenticated)
const currentUser = computed(() => authStore.user)

onMounted(async () => {
  const blogId = parseInt(route.params.id)
  if (!blogId) {
    router.push('/blogs')
    return
  }
  
  try {
    loading.value = true
    console.log('正在尝试获取博客ID:', blogId)
    
    const blogData = await blogStore.fetchBlogById(blogId)
    console.log('获取到的博客数据:', blogData)
    
    // 验证博客数据是否有效
    if (!blogData || !blogData.blogId) {
      throw new Error('获取到的博客数据无效')
    }
    
    blog.value = blogData
    
    // 加载评论
    await commentStore.fetchCommentsByBlog(blogId)
  } catch (error) {
    console.error('加载博客数据失败:', error)
    // 错误已记录，不需要额外操作，界面会显示"博客不存在"提示
  } finally {
    loading.value = false
  }
})

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

const formatImagePath = (imagePath) => {
  if (!imagePath) return '@/assets/default-avatar.png'
  
  // 如果是完整的image对象且有imageName属性，使用统一的图片URL格式
  if (typeof imagePath === 'object' && imagePath.imageName) {
    return `http://localhost:8080/api/image/${imagePath.imageName}`
  }
  
  // 如果包含完整路径（http或https），直接返回
  if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
    return imagePath
  }
  
  // 如果只有文件名，添加标准API路径
  if (!imagePath.includes('/') && !imagePath.includes('\\')) {
    return `http://localhost:8080/api/image/${imagePath}`
  }
  
  // 如果是相对路径但以/开头，去掉开头的/
  if (imagePath.startsWith('/')) {
    imagePath = imagePath.substring(1)
  }
  
  // 如果包含uploads/images目录，使用标准格式
  if (imagePath.includes('uploads/images')) {
    // 提取文件名
    const parts = imagePath.split('/')
    const fileName = parts[parts.length - 1]
    return `http://localhost:8080/api/image/${fileName}`
  }
  
  // 默认返回原始路径
  return imagePath
}

const handleAddComment = async () => {
  if (!isAuthenticated.value) {
    router.push(`/login?redirect=${route.fullPath}`)
    return
  }
  
  if (!commentContent.value.trim()) return
  
  try {
    commentLoading.value = true
    await commentStore.addComment({
      blogId: blog.value.blogId,
      content: commentContent.value
    })
    commentContent.value = ''
  } catch (error) {
    console.error('Failed to add comment:', error)
  } finally {
    commentLoading.value = false
  }
}

const showReplyForm = (commentId) => {
  if (!isAuthenticated.value) {
    router.push(`/login?redirect=${route.fullPath}`)
    return
  }
  activeReplyId.value = commentId
}

const handleAddReply = async (commentId) => {
  if (!replyContent.value.trim()) return
  
  try {
    replyLoading.value = true
    await commentStore.addReply({
      commentId: commentId,
      content: replyContent.value
    })
    replyContent.value = ''
    activeReplyId.value = null
  } catch (error) {
    console.error('Failed to add reply:', error)
  } finally {
    replyLoading.value = false
  }
}

const handleDeleteComment = async (commentId) => {
  if (confirm('确定要删除这条评论吗？')) {
    try {
      await commentStore.deleteComment(commentId)
    } catch (error) {
      console.error('Failed to delete comment:', error)
    }
  }
}

const handleDeleteReply = async (userId, commentId) => {
  if (confirm('确定要删除这条回复吗？')) {
    try {
      await commentStore.deleteReply(userId, commentId)
    } catch (error) {
      console.error('删除回复失败:', error)
      alert(error.message || '删除失败')
    }
  }
}

const handleLikeBlog = async () => {
  if (!isAuthenticated.value) {
    router.push(`/login?redirect=${route.fullPath}`)
    return
  }
  
  try {
    likeLoading.value = true
    await blogStore.likeBlog(blog.value.blogId)
    // 更新博客信息
    blog.value.likeCount = (blog.value.likeCount || 0) + 1
  } catch (error) {
    console.error('Failed to like blog:', error)
  } finally {
    likeLoading.value = false
  }
}

const goBack = () => {
  router.go(-1)
}

const goToAuthorBlogs = (authorId) => {
  router.push(`/blogs?author=${authorId}`)
}

const goToBlogsByType = (typeId) => {
  router.push({
    path: '/blogs',
    query: { type: typeId }
  })
}

const handleToggleCommentStatus = async (commentId, isDisabled) => {
  try {
    await commentStore.toggleCommentStatus(commentId, isDisabled)
  } catch (error) {
    console.error('修改评论状态失败:', error)
    alert(error.message || '操作失败')
  }
}

const handleToggleReplyStatus = async (userId, commentId, isDisabled) => {
  try {
    await axios.put(`/api/comment/admin/reply/toggle-status`, null, {
      params: { userId, commentId, isDisabled }
    })
    
    // 更新本地状态
    const updatedComments = comments.value.map(comment => {
      if (comment.commentId === commentId) {
        return {
          ...comment,
          replies: comment.replies?.map(reply => {
            if (reply.userId === userId && reply.commentId === commentId) {
              return { ...reply, isDisabled }
            }
            return reply
          })
        }
      }
      return comment
    })
    
    commentStore.comments = updatedComments
  } catch (error) {
    console.error('修改回复状态失败:', error)
    alert(error.message || '操作失败')
  }
}
</script>

<template>
  <DefaultLayout>
    <div class="blog-detail-page">
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
      </div>
      
      <template v-else-if="blog">
        <!-- 返回按钮 -->
        <div class="back-link">
          <button class="back-btn" @click="goBack">
            &larr; 返回
          </button>
        </div>
        
        <!-- 博客内容 -->
        <article class="blog-content">
          <header class="blog-header">
            <h1 class="blog-title">{{ blog.title }}</h1>
            <div class="blog-meta">
              <div class="meta-item author" @click="goToAuthorBlogs(blog.userId)">
                {{ blog.user?.name || '未知作者' }}
              </div>
              <div class="meta-item date">{{ formatDate(blog.createTime) }}</div>
              <div class="meta-item category" @click="goToBlogsByType(blog.typeId)">
                {{ blog.blogType?.typeName || '未分类' }}
              </div>
              <div class="meta-item views">{{ blog.views || 0 }} 阅读</div>
            </div>
          </header>
          
          <div v-if="blog.coverImage" class="blog-cover">
            <img :src="blog.coverImage" alt="博客封面" />
          </div>
          
          <div class="blog-body">
            <p v-html="blog.content"></p>
          </div>
          
          <div class="blog-actions">
            <button class="like-btn" @click="handleLikeBlog" :disabled="likeLoading">
              <span class="like-icon">❤️</span>
              <span class="like-count">{{ blog.likeCount || blog.likes || 0 }}</span>
            </button>
          </div>
        </article>
        
        <!-- 评论区 -->
        <section class="comments-section">
          <h2 class="section-title">评论 ({{ comments.length }})</h2>
          
          <!-- 评论表单 -->
          <div class="comment-form">
            <textarea 
              v-model="commentContent" 
              class="comment-textarea" 
              placeholder="发表你的评论..."
              rows="3"
            ></textarea>
            <div class="form-actions">
              <button 
                class="btn btn-primary comment-btn" 
                @click="handleAddComment" 
                :disabled="commentLoading || !commentContent.trim()"
              >
                <span v-if="commentLoading" class="loading-spinner-small"></span>
                <span v-else>发表评论</span>
              </button>
            </div>
          </div>
          
          <!-- 评论列表 -->
          <div v-if="comments.length === 0" class="empty-comments">
            暂无评论，快来发表第一条评论吧！
          </div>
          
          <div v-else class="comments-list">
            <div v-for="comment in comments" :key="comment.commentId" 
                 class="comment-item" 
                 :class="{ 'comment-disabled': comment.isDisabled }">
              <div class="comment-header">
                <div class="comment-author-info">
                  <img 
                    v-if="comment.user?.avatar?.imageName" 
                    :src="`http://localhost:8080/api/image/${comment.user.avatar.imageName}`" 
                    alt="头像" 
                    class="user-avatar" 
                    @error="e => e.target.src = require('@/assets/default-avatar.png')"
                  />
                  <img v-else src="@/assets/default-avatar.png" alt="默认头像" class="user-avatar" />
                  <div class="author-details">
                    <div class="comment-author">{{ comment.user?.name || '未知用户' }}</div>
                    <div class="comment-date">{{ formatDate(comment.createTime) }}</div>
                  </div>
                </div>
                <div v-if="comment.isDisabled" class="disabled-badge">已禁用</div>
              </div>
              
              <div class="comment-content" :class="{ 'content-disabled': comment.isDisabled }">
                {{ comment.isDisabled ? '此评论已被管理员禁用' : comment.content }}
              </div>
              
              <div class="comment-actions">
                <button 
                  v-if="!comment.isDisabled && isAuthenticated && currentUser.userId !== comment.userId" 
                  class="reply-btn" 
                  @click="showReplyForm(comment.commentId)"
                >
                  <i class="fa fa-reply"></i> 回复
                </button>
                
                <button 
                  v-if="isAuthenticated && (currentUser.userId === comment.userId || currentUser.isAdmin)" 
                  class="delete-btn" 
                  @click="handleDeleteComment(comment.commentId)"
                >
                  <i class="fa fa-trash"></i> 删除
                </button>
                
                <button 
                  v-if="isAuthenticated && currentUser.isAdmin" 
                  class="toggle-btn" 
                  @click="handleToggleCommentStatus(comment.commentId, !comment.isDisabled)"
                >
                  <i :class="comment.isDisabled ? 'fa fa-check-circle' : 'fa fa-ban'"></i>
                  {{ comment.isDisabled ? '启用' : '禁用' }}
                </button>
              </div>
              
              <!-- 回复表单 -->
              <div v-if="activeReplyId === comment.commentId" class="reply-form">
                <div class="reply-header">
                  <strong>回复 {{ comment.user?.name }}</strong>
                </div>
                <textarea
                  v-model="replyContent"
                  class="reply-textarea"
                  placeholder="输入回复内容..."
                  rows="2"
                ></textarea>
                <div class="form-actions">
                  <button 
                    class="btn btn-secondary cancel-btn" 
                    @click="activeReplyId = null"
                  >
                    取消
                  </button>
                  <button 
                    class="btn btn-primary reply-submit-btn" 
                    @click="handleAddReply(comment.commentId)" 
                    :disabled="replyLoading || !replyContent.trim()"
                  >
                    <span v-if="replyLoading" class="loading-spinner-small"></span>
                    <span v-else>提交回复</span>
                  </button>
                </div>
              </div>
              
              <!-- 回复列表 -->
              <div v-if="comment.replies && comment.replies.length > 0" class="replies-list">
                <div v-for="reply in comment.replies" :key="`${reply.userId}-${reply.commentId}`" 
                     class="reply-item"
                     :class="{ 'reply-disabled': reply.isDisabled }">
                  <div class="reply-header">
                    <div class="reply-author-info">
                      <img 
                        v-if="reply.user?.avatar?.imageName" 
                        :src="`http://localhost:8080/api/image/${reply.user.avatar.imageName}`" 
                        alt="头像" 
                        class="user-avatar-small" 
                        @error="e => e.target.src = require('@/assets/default-avatar.png')"
                      />
                      <img v-else src="@/assets/default-avatar.png" alt="默认头像" class="user-avatar-small" />
                      <div class="author-details">
                        <div class="reply-author">{{ reply.user?.name || '未知用户' }}</div>
                        <div class="reply-date">{{ formatDate(reply.createTime) }}</div>
                      </div>
                    </div>
                    <div v-if="reply.isDisabled" class="disabled-badge">已禁用</div>
                  </div>
                  
                  <div class="reply-content" :class="{ 'content-disabled': reply.isDisabled }">
                    {{ reply.isDisabled ? '此回复已被管理员禁用' : reply.content }}
                  </div>
                  
                  <div class="reply-actions">
                    <button 
                      v-if="isAuthenticated && (currentUser.userId === reply.userId || currentUser.isAdmin)" 
                      class="delete-btn" 
                      @click="handleDeleteReply(reply.userId, reply.commentId)"
                    >
                      <i class="fa fa-trash"></i> 删除
                    </button>
                    <button 
                      v-if="isAuthenticated && currentUser.isAdmin" 
                      class="toggle-btn" 
                      @click="handleToggleReplyStatus(reply.userId, reply.commentId, !reply.isDisabled)"
                    >
                      <i :class="reply.isDisabled ? 'fa fa-check-circle' : 'fa fa-ban'"></i>
                      {{ reply.isDisabled ? '启用' : '禁用' }}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
      </template>
      
      <div v-else class="not-found">
        <h2>博客不存在或已被删除</h2>
        <p class="error-message">抱歉，您请求的博客内容无法显示</p>
        <div class="action-buttons">
          <button @click="goBack" class="btn btn-secondary">返回上一页</button>
          <router-link to="/blogs" class="btn btn-primary">浏览其他博客</router-link>
        </div>
      </div>
    </div>
  </DefaultLayout>
</template>

<style scoped>
.blog-detail-page {
  padding: 1rem 0 3rem;
  background: var(--background);
  min-height: 100vh;
}

.back-link {
  margin-bottom: 1.5rem;
}

.back-btn {
  background: none;
  border: none;
  padding: 0.5rem 0;
  color: var(--primary-color);
  font-size: 1rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: color 0.2s;
}
.back-btn:hover {
  color: var(--accent-color);
}

.blog-content {
  background-color: var(--background-dark);
  border-radius: 14px;
  box-shadow: var(--card-shadow);
  padding: 2.5rem 2rem 2rem 2rem;
  margin-bottom: 2rem;
  transition: background 0.3s;
}

.blog-header {
  margin-bottom: 2rem;
}

.blog-title {
  font-size: 2.5rem;
  line-height: 1.3;
  margin-bottom: 1.5rem;
  font-weight: 700;
  color: var(--text-color);
}

.blog-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 1.5rem;
  color: var(--text-light);
  font-size: 0.95rem;
}

.meta-item {
  display: flex;
  align-items: center;
}

.meta-item.author, .meta-item.category {
  color: var(--primary-color);
  font-weight: 500;
  cursor: pointer;
}
.meta-item.author:hover, .meta-item.category:hover {
  color: var(--accent-color);
}

.blog-cover {
  margin: 1.5rem 0;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: var(--card-shadow);
}

.blog-cover img {
  width: 100%;
  max-height: 500px;
  object-fit: cover;
}

.blog-body {
  font-size: 1.13rem;
  line-height: 1.9;
  color: var(--text-color);
  margin-bottom: 2rem;
}

.blog-body p {
  margin-bottom: 1.5rem;
}

.blog-actions {
  display: flex;
  justify-content: center;
  margin-top: 3rem;
  gap: 1.5rem;
}

.like-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  background: var(--background-dark);
  border: 1.5px solid var(--border-color);
  border-radius: 50px;
  padding: 0.75rem 2rem;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 1rem;
  color: var(--primary-color);
  box-shadow: var(--card-shadow);
}
.like-btn:hover {
  border-color: var(--accent-color);
  background-color: var(--accent-color);
  color: #fff;
}
.like-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}
.like-icon {
  font-size: 1.25rem;
}

/* 评论区 */
.comments-section {
  background-color: var(--background-dark);
  border-radius: 14px;
  box-shadow: var(--card-shadow);
  padding: 2rem;
  margin-top: 2rem;
  transition: background 0.3s;
}
.section-title {
  font-size: 1.5rem;
  font-weight: 600;
  margin-bottom: 1.5rem;
  color: var(--text-color);
}
.comment-form {
  margin-bottom: 2rem;
}
.comment-textarea, .reply-textarea {
  width: 100%;
  padding: 1rem;
  border: 1.5px solid var(--border-color);
  border-radius: 8px;
  font-size: 1rem;
  resize: vertical;
  transition: border-color 0.2s, background 0.3s;
  margin-bottom: 1rem;
  background: var(--background);
  color: var(--text-color);
}
.comment-textarea:focus, .reply-textarea:focus {
  border-color: var(--primary-color);
  outline: none;
}
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}
.loading-spinner-small {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: var(--primary-color);
  animation: spin 1s linear infinite;
}
@keyframes spin {
  100% {
    transform: rotate(360deg);
  }
}
.empty-comments {
  padding: 2rem 0;
  text-align: center;
  color: var(--text-light);
}
.comments-list {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}
.comment-item {
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 1.5rem;
}
.comment-header, .reply-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.5rem;
}
.comment-author, .reply-author {
  font-weight: 500;
  color: var(--primary-color);
}
.comment-date, .reply-date {
  color: var(--text-light);
  font-size: 0.875rem;
}
.comment-content, .reply-content {
  margin-bottom: 1rem;
  line-height: 1.6;
  color: var(--text-color);
}
.comment-actions, .reply-actions {
  display: flex;
  gap: 1rem;
}
.reply-btn, .delete-btn {
  background: none;
  border: none;
  padding: 0;
  font-size: 0.875rem;
  color: var(--text-light);
  cursor: pointer;
  transition: color 0.2s;
}
.reply-btn:hover {
  color: var(--primary-color);
}
.delete-btn:hover {
  color: var(--error-color);
}
.reply-form {
  margin: 1rem 0;
  padding-left: 1.5rem;
  border-left: 3px solid var(--border-color);
}
.replies-list {
  margin-top: 1.5rem;
  padding-left: 1.5rem;
  border-left: 3px solid var(--border-color);
  display: flex;
  flex-direction: column;
  gap: 1rem;
}
.reply-item {
  padding-bottom: 1rem;
}
.reply-item:not(:last-child) {
  border-bottom: 1px dashed var(--border-color);
}
.not-found {
  text-align: center;
  padding: 3rem 1rem;
  margin: 2rem auto;
  max-width: 600px;
  background-color: var(--background-dark);
  border-radius: 12px;
  box-shadow: var(--card-shadow);
}
.not-found h2 {
  font-size: 1.8rem;
  margin-bottom: 1rem;
  color: var(--text-color);
}
.error-message {
  font-size: 1.1rem;
  color: var(--text-light);
  margin-bottom: 2rem;
}
.action-buttons {
  display: flex;
  gap: 1rem;
  justify-content: center;
}
@media (max-width: 768px) {
  .blog-content {
    padding: 1.5rem;
  }
  .blog-title {
    font-size: 1.75rem;
  }
  .blog-meta {
    gap: 1rem;
    flex-wrap: wrap;
  }
  .blog-body {
    font-size: 1rem;
  }
  .comments-section {
    padding: 1.5rem;
  }
  .action-buttons {
    flex-direction: column;
  }
}
.loading-container {
  display: flex;
  justify-content: center;
  padding: 5rem 0;
}
.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid rgba(74, 111, 165, 0.2);
  border-radius: 50%;
  border-top-color: var(--primary-color);
  animation: spin 1s linear infinite;
}
@media (max-width: 768px) {
  .blog-content {
    padding: 1.5rem;
  }
  .blog-title {
    font-size: 1.75rem;
  }
  .blog-meta {
    gap: 1rem;
    flex-wrap: wrap;
  }
  .blog-body {
    font-size: 1rem;
  }
  .comments-section {
    padding: 1.5rem;
  }
}
.debug-info {
  margin: 1.5rem 0;
  padding: 1rem;
  background: var(--background-dark);
  border-radius: 8px;
  text-align: left;
  font-family: monospace;
  line-height: 1.6;
  color: var(--text-light);
}

.comment-author-info, .reply-author-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.author-details {
  display: flex;
  flex-direction: column;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid var(--primary-color);
}

.user-avatar-small {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  object-fit: cover;
  border: 1.5px solid var(--primary-color);
}

.comment-disabled, .reply-disabled {
  opacity: 0.7;
  background-color: rgba(0, 0, 0, 0.02);
}

.content-disabled {
  font-style: italic;
  color: var(--text-light);
}

.disabled-badge {
  background-color: var(--error-color);
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 500;
}

.toggle-btn {
  background: none;
  border: none;
  padding: 0;
  font-size: 0.875rem;
  color: var(--text-light);
  cursor: pointer;
  transition: color 0.2s;
}

.toggle-btn:hover {
  color: var(--warning-color);
}

.comment-content, .reply-content {
  margin: 1rem 0;
  line-height: 1.6;
  color: var(--text-color);
  white-space: pre-wrap;
}

.debug-info {
  margin: 1.5rem 0;
  padding: 1rem;
  background: var(--background-dark);
  border-radius: 8px;
  text-align: left;
  font-family: monospace;
  line-height: 1.6;
  color: var(--text-light);
}
</style> 